package com.cardbaobao.cardbabyclient.ui.activity;

import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.GridLayoutHelper;
import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.alibaba.android.vlayout.layout.SingleLayoutHelper;
import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.activity.web.EventWebViewActivity;
import com.cardbaobao.cardbabyclient.ui.adapter.FeaturedRaidersDelegateAdapter;
import com.cardbaobao.cardbabyclient.ui.adapter.HotTopicDelegateAdapter;
import com.cardbaobao.cardbabyclient.ui.adapter.NoDataDelegateAdapter;
import com.cardbaobao.cardbabyclient.ui.adapter.RaidersFooterDelegateAdapter;
import com.cardbaobao.cardbabyclient.ui.adapter.RaidersLabelDelegateAdapter;
import com.cardbaobao.cardbabyclient.ui.adapter.RaidersTypeDelegateAdapter;
import com.cardbaobao.cardbabyclient.ui.adapter.WoolRaidersDelegateAdapter;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.callback.RecycleItemClickedCallback;
import com.cardbaobao.cardbabyclient.controller.CommonJumpController;
import com.cardbaobao.cardbabyclient.model.Banner;
import com.cardbaobao.cardbabyclient.model.CreditCardRaidersLayout;
import com.cardbaobao.cardbabyclient.model.result.BannerResult;
import com.cardbaobao.cardbabyclient.model.result.CreditCardRaidersLayoutResult;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.DensityUtil;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.ImageLoaderUtil;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.ScreenUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.utils.UmengEventUtils;
import com.cardbaobao.cardbabyclient.widget.TitleBar;
import com.gyf.barlibrary.ImmersionBar;
import com.stx.xhb.xbanner.XBanner;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by Jiangzx on 17:12.
 * 办卡攻略
 */
public class CreditCardRaidersActivity extends BaseActivity {
    public static final int RAIDERS_TOP_TYPE = 1;
    public static final int RAIDERS_MIDDLE_LABEL = 2;
    public static final int RAIDERS_HOT_TOPIC = 3;
    public static final int RAIDERS_FEATURED = 4;
    public static final int RAIDERS_WOOL = 5;
    public static final int RAIDERS_FOOTER = 6;
    @BindView(R.id.main_appbar)
    AppBarLayout appBarLayout;
    @BindView(R.id.title_bar)
    TitleBar titleBar;

    @BindView(R.id.xb_banner)
    XBanner xBanner;

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;

    private DelegateAdapter adapter;
    private List<DelegateAdapter.Adapter> adapters;

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);

        mCurrentPageId= Self.Page.app_credit_card_raiders_page;

        initIntent();
        ImmersionBar.with(this).statusBarDarkFont(true,Constant.STATUS_BAR_FONT_ALPHA).init();
        titleBar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        ViewGroup.LayoutParams params = xBanner.getLayoutParams();
        int width = ScreenUtil.getScreenWidth(mContext);
        params.height = (int) (width * 28 / 75.0f);
        xBanner.setLayoutParams(params);
        xBanner.setmAutoPalyTime(Constant.BANNER_INTERVAL_TIME);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    VirtualLayoutManager manager =
                            (VirtualLayoutManager) recyclerView.getLayoutManager();
                    if (manager.findFirstCompletelyVisibleItemPosition() == 0) {
                        appBarLayout.setExpanded(true, true);
                    }
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (xBanner.getParent() != null) {
            xBanner.startAutoPlay();
        }
        GoogleAnalyticsUtil.setScreenName(Google.CREDIT_RAIDERS);
        UmengEventUtils.pageEvent(mContext,getString(R.string.event_0x04c));
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (xBanner.getParent() != null) {
            xBanner.stopAutoPlay();
        }
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        loadBannerData();
        loadData();

        final VirtualLayoutManager layoutManager = new VirtualLayoutManager(mContext);
        final RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        viewPool.setMaxRecycledViews(RAIDERS_TOP_TYPE, 4);
        viewPool.setMaxRecycledViews(RAIDERS_MIDDLE_LABEL, 2);
        viewPool.setMaxRecycledViews(RAIDERS_HOT_TOPIC, 5);
        viewPool.setMaxRecycledViews(RAIDERS_FEATURED, 5);
        viewPool.setMaxRecycledViews(RAIDERS_WOOL, 5);
        recyclerView.setRecycledViewPool(viewPool);

        recyclerView.setLayoutManager(layoutManager);
        adapter = new DelegateAdapter(layoutManager, false);
        adapters = new LinkedList<>();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_credit_card_raiders;
    }

    /**
     * 获取轮播图数据
     */
    private void loadBannerData() {
        Observable<String> observable= Api.getBannerData(Constant.GLB0316);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                hideBanner();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                BannerResult bannerResult = JsonUtil.json2Object(s, BannerResult.class);
                if (bannerResult.getCode() == Constant.SUC_CODE) {
                    if (bannerResult.getData() != null) {
                        final List<Banner.CarouselFigureListBean> data =
                                bannerResult.getData().getCarousel_figure_list();
                        if (data != null && data.size() > 0) {
                            xBanner.stopAutoPlay();
                            xBanner.setData(data, null);
                            xBanner.setmAdapter(new XBanner.XBannerAdapter() {
                                @Override
                                public void loadBanner(XBanner banner, Object model, View view, int position) {
                                    ImageLoaderUtil.displayImage(URLUtil.CBB_IMG_URL + ((Banner.CarouselFigureListBean) model).getImage(),
                                            (ImageView) view);
                                }
                            });
                            xBanner.setOnItemClickListener(new XBanner.OnItemClickListener() {
                                @Override
                                public void onItemClick(XBanner banner, int position) {
                                    SelfUtils.buriedClickData(Self.Action.app_click_credit_card_raiders_top_banner,
                                            Self.Action.app_click_credit_card_raiders_top_banner_des,
                                            mEnterPageTime,
                                            mCurrentPageId,
                                            mPrePageId);
                                    CommonJumpController controller = new CommonJumpController(mContext);
                                    Banner.CarouselFigureListBean bean = data.get(position);
                                    Map<String, Object> extra = new HashMap<>();
                                    extra.put(CommonJumpController.FROM_PAGE, "办卡攻略-banner");
                                    extra.put(EventWebViewActivity.WEB_TYPE_I, 19);
                                    controller.bannerJump(bean, extra);
                                }
                            });
                            xBanner.startAutoPlay();
                        } else {
                            hideBanner();
                        }
                    } else {
                        hideBanner();
                    }
                } else {
                    hideBanner();
                    ToastUtil.showToast(bannerResult.getMsg());
                }
            }
        });
    }

    private void hideBanner() {
        appBarLayout.removeView(xBanner);
        //取消recyclerView顶部margin
        ViewGroup.MarginLayoutParams marginLayoutParams =
                (ViewGroup.MarginLayoutParams) recyclerView.getLayoutParams();
        marginLayoutParams.topMargin = 0;
        recyclerView.setLayoutParams(marginLayoutParams);
        //显示divider
        titleBar.showDivider();
    }

    /**
     * 设置分类数据
     */
    private void setTypeUi(final List<CreditCardRaidersLayout.UpperMenu> data) {
        if (data.size() == 0) {
            return;
        }
        GridLayoutHelper raidersTypeHelper = new GridLayoutHelper(4);
        RaidersTypeDelegateAdapter raidersTypeAdapter =
                new RaidersTypeDelegateAdapter(raidersTypeHelper, data);
        raidersTypeAdapter.setRecycleItemClickedCallback(new RecycleItemClickedCallback() {
            @Override
            public void onRecycleItemClicked(int position) {
                String typeCode=data.get(position).getCode();
                if(Constant.JBQ01060401.equals(typeCode)){
                    //办卡
                    SelfUtils.buriedClickData(Self.Action.app_click_credit_card_raiders_credit_card,
                            Self.Action.app_click_credit_card_raiders_credit_card_des,
                            mEnterPageTime,
                            mCurrentPageId,
                            mPrePageId);
                }else if(Constant.JBQ01060402.equals(typeCode)){
                    //提额
                    SelfUtils.buriedClickData(Self.Action.app_click_credit_card_raiders_upper_quota,
                            Self.Action.app_click_credit_card_raiders_upper_quota_des,
                            mEnterPageTime,
                            mCurrentPageId,
                            mPrePageId);
                }else if(Constant.JBQ01060403.equals(typeCode)){
                    //羊毛
                    SelfUtils.buriedClickData(Self.Action.app_click_credit_card_raiders_wool,
                            Self.Action.app_click_credit_card_raiders_wool_des,
                            mEnterPageTime,
                            mCurrentPageId,
                            mPrePageId);
                }else if(Constant.JBQ01060404.equals(typeCode)){
                    //专题
                    SelfUtils.buriedClickData(Self.Action.app_click_credit_card_raiders_topic,
                            Self.Action.app_click_credit_card_raiders_topic_des,
                            mEnterPageTime,
                            mCurrentPageId,
                            mPrePageId);
                }
                mIntent.setClass(mContext, CreditCardRaidersFilterActivity.class);
                mIntent.putExtra(CreditCardRaidersFilterActivity.RAIDERS_TYPE,
                        typeCode);
                mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                startActivity(mIntent);
            }
        });
        adapters.add(raidersTypeAdapter);
    }

    /**
     * 设置热门专题数据
     */
    private void setTopicUi(final List<CreditCardRaidersLayout.HotTopic> data) {
        if (data.size() == 0) {
            return;
        }
        SingleLayoutHelper topicLabelHelper = new SingleLayoutHelper();
        adapters.add(new RaidersLabelDelegateAdapter(topicLabelHelper, "热门专题"));
        GridLayoutHelper topicContentHelper =
                new GridLayoutHelper(2, data.size(), 1, 1);
        topicContentHelper.setBgColor(0xffeeeeee);
        HotTopicDelegateAdapter topicDelegateAdapter =
                new HotTopicDelegateAdapter(topicContentHelper, data);
        topicDelegateAdapter.setRecycleItemClickedCallback(new RecycleItemClickedCallback() {
            @Override
            public void onRecycleItemClicked(int position) {
                //跳web
                CreditCardRaidersLayout.HotTopic topic = data.get(position);
                String webUrl = topic.getUrl();
                String webTitle = topic.getName();
                if (!TextUtils.isEmpty(webUrl)) {
                    SelfUtils.buriedClickData(Self.Action.app_click_credit_card_raiders_hot_topic_item,
                            Self.Action.app_click_credit_card_raiders_hot_topic_item_des,
                            mEnterPageTime,
                            mCurrentPageId,
                            mPrePageId);
                    mIntent.setClass(mContext, EventWebViewActivity.class);
                    mIntent.putExtra(EventWebViewActivity.WEB_URL_S, URLUtil.CBB_WEB_URL + webUrl);
                    mIntent.putExtra(EventWebViewActivity.WEB_TITLE_S, webTitle);
                    mIntent.putExtra(EventWebViewActivity.WEB_TYPE_I, 20);
                    mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                    startActivity(mIntent);
                }
            }
        });
        adapters.add(topicDelegateAdapter);
    }

    /**
     * 设置精选攻略数据
     */
    private void setFeaturedRaidersUi(final List<CreditCardRaidersLayout.FeaturedRaiders> data) {
        if (data.size() > 0) {
            SingleLayoutHelper featuredHelper = new SingleLayoutHelper();
            adapters.add(new RaidersLabelDelegateAdapter(featuredHelper, "精选攻略"));
            LinearLayoutHelper featuredContentHelper = new LinearLayoutHelper();
            FeaturedRaidersDelegateAdapter adapter =
                    new FeaturedRaidersDelegateAdapter(featuredContentHelper, data);
            adapter.setRecycleItemClickedCallback(new RecycleItemClickedCallback() {
                @Override
                public void onRecycleItemClicked(int position) {
                    CreditCardRaidersLayout.FeaturedRaiders raiders = data.get(position);
                    String webUrl = raiders.getUrl();
                    String webTitle = raiders.getTitle();
                    if (!TextUtils.isEmpty(webUrl)) {
                        SelfUtils.buriedClickData(Self.Action.app_click_credit_card_raiders_featured_raiders_item,
                                Self.Action.app_click_credit_card_raiders_featured_raiders_item_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                mPrePageId);
                        mIntent.setClass(mContext, EventWebViewActivity.class);
                        mIntent.putExtra(EventWebViewActivity.WEB_URL_S,
                                URLUtil.CBB_WEB_URL + webUrl);
                        mIntent.putExtra(EventWebViewActivity.WEB_TITLE_S,
                                webTitle);
                        mIntent.putExtra(EventWebViewActivity.WEB_TYPE_I, 21);
                        mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                        startActivity(mIntent);
                    }
                }
            });
            adapters.add(adapter);
        }
    }

    /**
     * 设置羊毛攻略数据
     */
    private void setWoolRaidersUi(final List<CreditCardRaidersLayout.WoolRaiders> data) {
        if (data.size() > 0) {
            SingleLayoutHelper woolHelper = new SingleLayoutHelper();
            adapters.add(new RaidersLabelDelegateAdapter(woolHelper, "羊毛攻略"));
            LinearLayoutHelper woolContentHelper = new LinearLayoutHelper();
            WoolRaidersDelegateAdapter adapter = new WoolRaidersDelegateAdapter(woolContentHelper, data);
            adapter.setRecycleItemClickedCallback(new RecycleItemClickedCallback() {
                @Override
                public void onRecycleItemClicked(int position) {
                    CreditCardRaidersLayout.WoolRaiders raiders =
                            data.get(position);
                    String webUrl = raiders.getUrl();
                    String webTitle = raiders.getName();
                    if (!TextUtils.isEmpty(webUrl)) {
                        SelfUtils.buriedClickData(Self.Action.app_click_credit_card_raiders_wool_raiders_item,
                                Self.Action.app_click_credit_card_raiders_wool_raiders_item_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                mPrePageId);
                        mIntent.setClass(mContext, EventWebViewActivity.class);
                        mIntent.putExtra(EventWebViewActivity.WEB_URL_S,
                                webUrl);
                        mIntent.putExtra(EventWebViewActivity.WEB_TITLE_S,
                                webTitle);
                        mIntent.putExtra(EventWebViewActivity.WEB_TYPE_I, 22);
                        mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                        startActivity(mIntent);
                    }
                }
            });
            adapters.add(adapter);
            //加载底部布局
            RaidersFooterDelegateAdapter footerDelegateAdapter = new RaidersFooterDelegateAdapter();
            footerDelegateAdapter.setRecycleItemClickedCallback(new RecycleItemClickedCallback() {
                @Override
                public void onRecycleItemClicked(int position) {

                    SelfUtils.buriedClickData(Self.Action.app_click_credit_card_raiders_more_raiders,
                            Self.Action.app_click_credit_card_raiders_more_raiders_des,
                            mEnterPageTime,
                            mCurrentPageId,
                            mPrePageId);

                    mIntent.setClass(mContext, CreditCardRaidersFilterActivity.class);
                    mIntent.putExtra(CreditCardRaidersFilterActivity.RAIDERS_TYPE,
                            Constant.JBQ01060403);
                    mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                    startActivity(mIntent);
                }
            });
            adapters.add(footerDelegateAdapter);
        }
    }

    private void loadData() {
        Observable<String> observable=Api.getCreditCardRaiders();
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
                if (recyclerView.getAdapter() == null) {
                    recyclerView.setAdapter(adapter);
                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
                if (recyclerView.getAdapter() == null) {
                    recyclerView.setAdapter(adapter);
                }
            }

            @Override
            public void onNext(String s) {
                CreditCardRaidersLayoutResult raidersResult =
                        JsonUtil.json2Object(s, CreditCardRaidersLayoutResult.class);
                if (raidersResult != null) {
                    if (raidersResult.getCode() == Constant.SUC_CODE) {
                        if (raidersResult.getData() != null) {
                            if (raidersResult.getData().getUpperMenu() != null) {
                                setTypeUi(raidersResult.getData().getUpperMenu());
                            }
                            if (raidersResult.getData().getHotSubject() != null) {
                                setTopicUi(raidersResult.getData().getHotSubject());
                            }
                            if (raidersResult.getData().getNewlists() != null) {
                                setFeaturedRaidersUi(raidersResult.getData().getNewlists());
                            }
                            if (raidersResult.getData().getPullMoney() != null) {
                                setWoolRaidersUi(raidersResult.getData().getPullMoney());
                            }
                            if (adapters.size() > 0) {
                                adapter.setAdapters(adapters);
                            } else {
                                adapters.add(new NoDataDelegateAdapter());
                                adapter.setAdapters(adapters);
                            }
                        }
                    } else {
                        ToastUtil.showToast(raidersResult.getMsg());
                    }
                }
            }
        });
    }
}
